<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\Wechat\AppletAuthController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceTotal;
use App\Models\ResourceTypeExternal;
use App\Validate\ResourceBusinessNameValidate;


use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

/**
 * 资源商管理
 */
class ResourceBusinessNameController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->validate = new ResourceBusinessNameValidate();
        $this->model = new ResourceBusinessName();
    }

    /**
     *  资源商(用于下拉框选择)筛选列表
     */
    public function filterList()
    {
        $condition[] = ['is_del', '=', 1];
        $manage_resource_business_ids = $this->request->manage_info['resource_business_ids'];

        if ($manage_resource_business_ids) {
            $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
            //使用in，只能用这种方式
            $condition[] = [
                function ($query) use ($manage_resource_business_ids) {
                    $query->whereIn('id', $manage_resource_business_ids);
                }
            ];
        }

        return $this->model->getFilterList(['id', 'name'], $condition, 'sort asc,id desc');
    }

    /**
     * 获取资源商列表
     * @param keywords 检索条件
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function lists()
    {
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);
        $res = $this->model->lists($this->request->all());
        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        $resourceTotalModel = new ResourceTotal();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            $model = $resourceTotalModel->getResourceTotalModel($val['id']);
            $res['data'][$key]['browse_num'] = $model ? $model->selectRaw('SUM(browse_num) as total')->value('total') : 0; //获取浏览量
            // $res['data'][$key]['resource_num'] = $resourceTotalModel->getResourceNum($val['id']);
        }
        //增加序号
        // $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        $res = $this->disPageData($res);
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 根据资源商获取对应类型列表
     * @param resource_business_id  资源商id
     * @param big_type_id 系统大类
     * @param keywords 检索数据
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getResourceTypeListByBusinessNameId()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_resource_type_list_by_business_name_id')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $resource_business_id = $this->request->resource_business_id;
        $big_type_id = $this->request->big_type_id;
        $keywords = $this->request->keywords;
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);

        $resourceTypeExternalModel = new ResourceTypeExternal();
        $res = $resourceTypeExternalModel->getResourceTypeList($resource_business_id, $big_type_id, $keywords, null, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        $resourceTotalModel = new ResourceTotal();
        foreach ($res['data'] as $key => $val) {
            $model = $resourceTotalModel->getResourceTotalModel($resource_business_id);
            $res['data'][$key]['browse_num'] = $model ? $model->where('type_id', $val['id'])->selectRaw('SUM(browse_num) as total')->value('total') : 0; //获取浏览量
            //   $res['data'][$key]['resource_num'] = $resourceTotalModel->getResourceNum($resource_business_id, null, $val['id']);
        }

        //增加序号
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        $res = $this->disPageData($res);
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 根据资源商获取对应（筛选）类型列表  (暂不使用，删除)
     * @param resource_business_id  资源商id
     * @param keywords 检索数据
     */
    public function _getResourceTypeFilterListByBusinessNameId()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_resource_type_filter_list_by_business_name_id')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $resource_business_id = $this->request->resource_business_id;
        $keywords = $this->request->keywords;

        $resourceTypeExternalModel = new ResourceTypeExternal();
        $res = $resourceTypeExternalModel->getResourceTypeList($resource_business_id, null, $keywords, null, 99999);
        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        return $this->returnApi(200, '获取成功', true, $res['data']); //筛选列表，只返回数据，不返回分页信息
    }

    /**
     * 根据资源商id获取资源
     * @param keywords 检索条件
     * @param resource_business_id 资源商id  (不传表示全部)
     * @param big_type_id 系统大类
     * @param type_id 系统小类
     * @param page int 当前页
     * @param limit int 分页大小
     * @param sort 排序字段 null 1 默认排序 2 浏览量排序 3 出版社排序
     * @param is_recom 是否推荐  1 推荐 2 不推荐
     */
    public function getResourceListByBusinessNameId()
    {
        //增加验证场景进行验证
        // if (!$this->validate->scene('get_resource_list_by_business_name_id')->check($this->request->all())) {
        //     return $this->returnApi(201,  $this->validate->getError());
        // }
        $resource_business_id = $this->request->resource_business_id;
        $keywords = $this->request->keywords;
        $big_type_id = $this->request->big_type_id;
        $type_id = $this->request->type_id;
        $sort = $this->request->sort;
        $is_recom = $this->request->is_recom;
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);

        $resourceTotalModel = new ResourceTotal();
        $res = $resourceTotalModel->getResourceListByBusinessNameId($keywords, $resource_business_id, $big_type_id, $type_id, $sort, $is_recom, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        $resourceTypeExternalModel = new ResourceTypeExternal();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['resource_business_name'] = !empty($val['resource_business_id']) ? ResourceBusinessName::getBusinessName($val['resource_business_id']) : '';
            $res['data'][$key]['type_name'] = !empty($val['type_id']) ? $resourceTypeExternalModel->where('id', $val['type_id'])->where('is_del', 1)->value('type_name') : '';

           
        }
        //增加序号
        // $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        $res['data'] = $this->disDataSameLevel($res['data'], 'con_big_type', ['type_name' => 'big_type_name']);
        $res = $this->disPageData($res);
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 自动同步数据，使用程序自动调用命令行执行同步操作
     * @param resource_business_id 资源商id
     */
    public function syncData()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sync_data')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $resource_business_id = $this->request->resource_business_id;
        $resource_business_info = $this->model->where('id', $resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_info)) {
            return $this->returnApi(202, '此资源商不存在');
        }
        if (in_array($resource_business_id, [2, 4, 7])) {
            //QQ阅读，博看   同步很慢  72小时只能同步一次
            if (!empty($resource_business_info['request_time']) && strtotime($resource_business_info['request_time']) > strtotime("-72 hour")) {
                return $this->returnApi(202, '72小时之内只能同步1次，请稍后重试！');
            }
        } else {
            if (!empty($resource_business_info['request_time']) && strtotime($resource_business_info['request_time']) > strtotime("-24 hour")) {
                return $this->returnApi(202, '24小时之内只能同步1次，请稍后重试！');
            }
        }

        $resource_business_info->request_time = date('Y-m-d H:i:s');
        $resource_business_info->save(); //更新同步时间

        switch ($resource_business_id) {
            case 1:
                $command = 'command:ZwzxMysqlData';
                break;
            case 2:
                $command = 'command:QqrdMysqlData';
                break;
            case 3:
                $command = 'command:YtysMysqlData';
                break;
            case 4:
                $command = 'command:BkMysqlData';
                break;
            // case 5:
            //     $command = 'command:';//乐儿数据，不支持
            //     break;
            case 6:
                $command = 'command:XytsMysqlData';
                break;
            case 7:
                $command = 'command:CxzxMysqlData';
                break;
            case 8:
                $command = 'command:ZyMysqlData';
                break;
            case 999:
                $command = 'command:CdbtMysqlData';
                break;
            default:
                $command = false;
        }
        if (empty($command)) {
            return $this->returnApi(202, '暂不支持该资源商数据同步');
        }
        $artisan = App::make(Kernel::class);
        $artisan->call($command, [
            // '--option' => 'value',
        ]);
        //无返回值，直接返回成功
        return $this->returnApi(200, '同步成功', true);
    }


    /**
     *修改模版
     * @param resource_business_id 资源商id
     * @param template 模版id
     */
    public function changeTemplate()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change_template')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->where('id', $this->request->resource_business_id)->update(['template' => $this->request->template, 'change_time' => date('Y-m-d H:i:s')]);
        if ($res) {
            return $this->returnApi(200, '修改成功', true);
        }
        return  $this->returnApi(202, '修改失败');
    }

    /**
     * 数字资源排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最小
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);
        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 隐藏 和 显示
     * @param id int 活动id
     * @param is_auto_show int 是否自动显示（追加）在微信端首页  1 显示   2 不显示
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->id, 'is_auto_show', $this->request->is_auto_show);

            $is_auto_show = $this->request->is_auto_show == 1 ? '显示' : '隐藏';

            DB::commit();
            return $this->returnApi($code, $is_auto_show . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
